package com.northpool.operator.common.file;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.CharsetUtil;
import com.northpool.operator.annotation.InputParam;
import com.northpool.operator.annotation.InputParams;
import com.northpool.operator.annotation.OperatorInfo;
import com.northpool.operator.annotation.OutputParam;
import com.northpool.operator.annotation.OutputParams;
import com.northpool.operator.annotation.ParamEnum;
import com.northpool.operator.annotation.ParamEnums;
import com.northpool.operator.common.algorithm.OperatorTestBuild;
import com.northpool.operator.common.algorithm.TestParamBuilder;
import com.northpool.operator.param.ParamTool;
import com.northpool.operator.type.TypeEnum;
import com.northpool.operator.utils.StpOperatorHelper;

import java.io.File;
import java.nio.charset.Charset;

@OperatorInfo(
        ref = "FileContentReadOperator",
        name = "文件内容读取",
        description = "读取文件内容",
        enums = {
                @ParamEnums(ref = "fileEncoding", value = {
                        @ParamEnum(ref = "utf-8", name = "utf-8"),
                        @ParamEnum(ref = "gbk", name = "gbk")
                }),
        }
)
@OutputParams({
        @OutputParam(ref = "fileContent", name = "文件内容", desc = "文件内容")
})
public class FileContentReadOperator extends StpOperatorHelper {

    @InputParams({
            @InputParam(ref = "filePath", name = "文件路径", desc = "文件路径", required = true),
            @InputParam(ref = "fileEncoding", name = "文件编码", desc = "文件编码", required = true, type = TypeEnum.ENUM, value = "utf-8")
    })
    public FileContentReadOperator() {
    }

    public static void main(String[] args) {
        OperatorTestBuild.execute(FileContentReadOperator.class, TestParamBuilder.aBuilder()
                .param("filePath", "D:\\Key.txt")
                .param("fileEncoding", "utf-8")
                .build()
        );
    }

    @Override
    public void execute(ParamTool paramTool) throws Exception {
        String filePath = paramTool.getStr("filePath");
        String fileEncoding = paramTool.getStr("fileEncoding");

        Charset charset = CharsetUtil.charset(fileEncoding);
        File file = FileUtil.file(filePath);
        if (!file.exists()) {
            this.error("文件不存在：" + filePath);
            this.failedExit();
        }

        String content = FileUtil.readString(file, charset);
        // 如果文件大于2MB
        if (file.length() > 2 * 1024 * 1024) {
            this.log("文件超过2MB，输出日志可能会对执行性能有影响，日志中将不输出文件内容");
            this.result("fileContent", content, false);
        } else {
            this.result("fileContent", content);
        }
    }
}
